import json
import time
from influxdb_client import InfluxDBClient, Point
from influxdb_client.client.write_api import SYNCHRONOUS

from utils.common import load_from_json
from train_procedure import execute_train_task

class BTSystem:
    def __init__(self):
        self.client = InfluxDBClient(url="http://localhost:8086", token="wOo9G5ib9wtH9JDFjjpb29C9CWmu0C-ZY01-Q6nuOGEBqLN9VJMcggSEH-Z9jY3etBBUlyZC7DQVRbPSNATUGg==", org="tellw.org") # 以前的老代码

        buckets_api=self.client.buckets_api()
        buckets=buckets_api.find_buckets().buckets
        bucket_names=[]
        for bucket in buckets:
            bucket_names.append(bucket.name)

        if 'btresults' not in bucket_names:
            buckets_api.create_bucket(bucket_name='btresults',org='tellw.org')

        self.write_api = self.client.write_api(write_options=SYNCHRONOUS)
        self.asr_bt_json=load_from_json('asr-bt.json')
        while len(self.asr_bt_json['tasks'])!=0:
            bttask_json=load_from_json(f'jsons/bttasks/{self.asr_bt_json["tasks"][0].json}')
            if bttask_json['type']=='train':
                execute_train_task(bttask_json,self.write_api)
            elif bttask_json['type']=='infer':
                execute_infer_task(bttask_json,self.write_api)
        self.status='starting'

    def end(self):
        self.client.close()
    
    def main(self,q):
        q.put('starting')
        while True:
            if len(self.tasks['tasks']):
                self.status='busy'
                q.put(self.status)
                task=self.tasks['tasks'][0]
                tt=Task(task['name'],task['dataset'],task['model'],task['preprocessor'],self.conf)
                # tt.exec()
                time.sleep(10)
                with open(self.conf['tasks'],encoding='utf8') as f:
                    ntasks=json.load(f)
                for t in ntasks['tasks']:
                    if t['name']==task['name']:
                        ntasks['tasks'].remove(t)
                # with open(self.conf['tasks'],'w',encoding='utf8') as f:
                #     json.dump(ntasks,f,ensure_ascii=False,indent=4)
                self.tasks=ntasks
            else:
                self.status='idle'
                q.put(self.status)
                time.sleep(self.conf['no_task_heart'])
                with open(self.conf['tasks'],encoding='utf8') as f:
                    self.tasks=json.load(f)

    def getStatus(self):
        return self.status